import sqlite3
import chat.client.gol


def create_username_database(user_id, user_name, password, email, private_key, private_key_n, plain_passwd):
    username_db = user_name
    conn = sqlite3.connect(username_db + '.db')
    print("数据库打开成功")

    def get_cursor():
        return conn.cursor()

    c = get_cursor()
    c.execute('''CREATE TABLE if not exists personal_room (
                       "room_id" INTEGER,
                       "room_name" TEXT,
                       "room_private_key" TEXT,
                       "room_private_key_n" TEXT,
                       "room_public_key" TEXT
    )               ;''')
    conn.commit()
    c.execute('''CREATE TABLE if not exists personal_information (
                    "user_id" integer NOT NULL ,
                    "user_name" text ,
                    "password" text ,
                    "email" text NOT NULL,
                    "private_key_bypwd" text,
                    "private_key_byemail" text,
                    "private_key_n" text
        )               ;''')
    conn.commit()
    c.execute(
        "INSERT into personal_information (user_id,user_name,password,email,private_key_bypwd,private_key_byemail,private_key_n)values (?,?,?,?,?,?,?)",
        [user_id, user_name, password, email, private_key, private_key, private_key_n])
    conn.commit()
    encrypt_private_key_bypwd(user_name, plain_passwd)
    encrypt_private_key_byemail(user_name, email)
    conn.close()


def create_database_connect(user_name):
    print(user_name)
    username_db = user_name
    username_db = ''.join(username_db)
    conn = sqlite3.connect(username_db + '.db')
    print("数据库打开成功")
    return conn


def return_user_pkey(user_name):
    '''返回pkey'''
    conn = create_database_connect(user_name)
    c = conn.cursor()
    if chat.client.gol.get_value("login_flag") == "username":
        private_key = \
        c.execute("select private_key_bypwd from personal_information where user_name=?", [user_name]).fetchone()[0]
    else:
        private_key = \
        c.execute("select private_key_byemail from personal_information where user_name=?", [user_name]).fetchone()[0]
    conn.commit()
    print(private_key)
    return private_key


def return_user_pkey_n(user_name):
    '''返回pkey——n'''
    conn = create_database_connect(user_name)
    c = conn.cursor()
    private_key_n = \
    c.execute("select private_key_n from personal_information where user_name=?", [user_name]).fetchone()[0]
    conn.commit()
    print(private_key_n)
    return private_key_n


def get_user_id(user_name):
    """返回user_name"""
    print(">>", user_name)
    conn = create_database_connect(user_name)
    c = conn.cursor()
    user_id = c.execute("select user_id from personal_information where user_name=?", [user_name]).fetchone()[0]
    conn.commit()
    print(user_id)
    return user_id


def return_room_public_key(user_name, room_id):
    '''返回room_public_key'''
    conn = create_database_connect(user_name)
    c = conn.cursor()
    room_public_key = c.execute("select room_public_key from personal_room where room_id =?", [room_id]).fetchone()[0]
    conn.commit()
    print(room_public_key)
    return room_public_key


def return_room_private_key_n(user_name, room_id):
    '''返回room_private_key_n'''
    conn = create_database_connect(user_name)
    c = conn.cursor()
    room_private_key_n = \
    c.execute("select room_private_key_n from personal_room where room_id =?", [room_id]).fetchone()[0]
    conn.commit()
    print(room_private_key_n)
    return room_private_key_n


def return_room_private_key(user_name, room_id):
    '''返回room_private_key_n'''
    conn = create_database_connect(user_name)
    c = conn.cursor()
    room_private_key = c.execute("select room_private_key from personal_room where room_id =?", [room_id]).fetchone()[0]
    conn.commit()
    print(room_private_key)
    return room_private_key


def update_user_room(user_name, room_id, room_name, room_private_key, room_private_key_n, room_public_key):
    '''将提供的user的room信息存入表中'''
    conn = create_database_connect(user_name)
    c = conn.cursor()
    result = c.execute("select * from personal_room where room_id = ?",(room_id,)).fetchone()
    if result == None:
        c.execute(
            "insert into personal_room (room_id,room_name,room_private_key,room_private_key_n,room_public_key) values (?,?,?,?,?)",
            (room_id, room_name, room_private_key, room_private_key_n, room_public_key))
        conn.commit()

def insert_private_key_personal_information_bypwd(user_name, private_key_bypwd):  # 插入个人信息的私钥
    conn = create_database_connect(user_name)
    c = conn.cursor()
    c.execute("UPDATE personal_information set private_key_bypwd=? WHERE user_name=?", [private_key_bypwd, user_name])
    conn.commit()


def insert_private_key_personal_information_byemail(user_name, private_key_byemail):  # 插入个人信息的私钥
    conn = create_database_connect(user_name)
    c = conn.cursor()
    c.execute("UPDATE personal_information set private_key_byemail=? WHERE user_name=?",
              [private_key_byemail, user_name])
    conn.commit()


def encrypt_private_key_bypwd(user_name, password):
    conn = create_database_connect(user_name)
    c = conn.cursor()
    before_encrypt_private_key = c.execute("SELECT private_key_bypwd from personal_information where user_name=?",
                                           [user_name]).fetchone()
    message = before_encrypt_private_key[0]
    print(message)
    key1 = password
    ml = len(message)  # 分别得到密钥和明文的长度
    kl = len(key1)
    result1 = []
    if kl < ml:
        key1 = ml // kl * key1 + key1[:ml % kl]
        for j in range(len(key1)):
            result1.append(chr(ord(message[j]) ^ ord(key1[j])))  # 跟KEY异或回去就是原明文
        result1 = ''.join(result1)
    else:
        # temp = kl
        # kl = ml
        # ml = temp
        # key = ml // kl * key + key[:ml % kl]
        key1 = key1[:ml + 1]
        for j in range(len(message)):
            result1.append(chr(ord(message[j]) ^ ord(key1[j])))  # 跟KEY异或回去就是原明文
        result1 = ''.join(result1)
    insert_private_key_personal_information_bypwd(user_name, result1)


def encrypt_private_key_byemail(user_name, email):
    conn = create_database_connect(user_name)
    c = conn.cursor()
    before_encrypt_private_key = c.execute("SELECT private_key_byemail from personal_information where user_name=?",
                                           [user_name]).fetchone()
    message = before_encrypt_private_key[0]
    print(message)
    key1 = email
    ml = len(message)  # 分别得到密钥和明文的长度
    kl = len(key1)
    result1 = []
    if kl < ml:
        key1 = ml // kl * key1 + key1[:ml % kl]
        for j in range(len(key1)):
            result1.append(chr(ord(message[j]) ^ ord(key1[j])))  # 跟KEY异或回去就是原明文
        result1 = ''.join(result1)
    else:
        # temp = kl
        # kl = ml
        # ml = temp
        # key = ml // kl * key + key[:ml % kl]
        key1 = key1[:ml + 1]
        for j in range(len(message)):
            result1.append(chr(ord(message[j]) ^ ord(key1[j])))  # 跟KEY异或回去就是原明文
        result1 = ''.join(result1)
    insert_private_key_personal_information_byemail(user_name, result1)


def decrypt_private_key_bypwd(user_name, password):
    conn = create_database_connect(user_name)
    c = conn.cursor()
    before_decrypt_private_key = c.execute("SELECT private_key_bypwd from personal_information where user_name=?",
                                           [user_name]).fetchone()
    message = before_decrypt_private_key[0]
    print(message)
    key = password
    ml = len(message)  # 分别得到密钥和明文的长度
    kl = len(key)
    result = []
    if kl < ml:
        key = ml // kl * key + key[:ml % kl]
        for j in range(len(key)):
            result.append(chr(ord(message[j]) ^ ord(key[j])))  # 跟KEY异或回去就是原明文
        result = ''.join(result)
    else:
        # temp = kl
        # kl = ml
        # ml = temp
        # key = ml // kl * key + key[:ml % kl]
        key = key[:ml]
        for j in range(len(key)):
            result.append(chr(ord(message[j]) ^ ord(key[j])))  # 跟KEY异或回去就是原明文
        result = ''.join(result)
    insert_private_key_personal_information_bypwd(user_name, result)


def decrypt_private_key_byemail(user_name, email):
    conn = create_database_connect(user_name)
    c = conn.cursor()
    before_decrypt_private_key = c.execute("SELECT private_key_byemail from personal_information where user_name=?",
                                           [user_name]).fetchone()
    message = before_decrypt_private_key[0]
    print(message)
    key = email
    ml = len(message)  # 分别得到密钥和明文的长度
    kl = len(key)
    result = []
    if kl < ml:
        key = ml // kl * key + key[:ml % kl]
        for j in range(len(key)):
            result.append(chr(ord(message[j]) ^ ord(key[j])))  # 跟KEY异或回去就是原明文
        result = ''.join(result)
    else:
        # temp = kl
        # kl = ml
        # ml = temp
        # key = ml // kl * key + key[:ml % kl]
        key = key[:ml]
        for j in range(len(key)):
            result.append(chr(ord(message[j]) ^ ord(key[j])))  # 跟KEY异或回去就是原明文
        result = ''.join(result)
    insert_private_key_personal_information_byemail(user_name, result)


def encrypt_room_private_key(user_name, type):
    conn = create_database_connect(user_name)
    c = conn.cursor()
    if type == "username":
        private_key = \
        c.execute("SELECT private_key_bypwd from personal_information where user_name=?", [user_name]).fetchone()[0]
    if type == "email":
        private_key = \
        c.execute("SELECT private_key_byemail from personal_information where user_name=?", [user_name]).fetchone()[0]
    # print(private_key)
    # room_private_key_list=[]
    room_private_keys = c.execute("SELECT room_private_key from personal_room").fetchall()
    for room_private_key in room_private_keys:
        message = ''.join(room_private_key[0])
        # print(message)
        key1 = ''.join(private_key)
        ml = len(message)  # 分别得到密钥和明文的长度
        kl = len(key1)
        result1 = []
        if kl < ml:
            key1 = ml // kl * key1 + key1[:ml % kl]
            for j in range(len(key1)):
                result1.append(chr(ord(message[j]) ^ ord(key1[j])))  # 跟KEY异或回去就是原明文
            result1 = ''.join(result1)
        else:
            key1 = key1[:ml + 1]
            for j in range(len(message)):
                result1.append(chr(ord(message[j]) ^ ord(key1[j])))  # 跟KEY异或回去就是原明文
            result1 = ''.join(result1)
        print(result1)
        c.execute("UPDATE personal_room SET room_private_key=? where room_private_key=?", [result1, message])
        conn.commit()
